<template>
	<view>
		<uvsticky offset-top="0">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text" activeColor="#ff4a82"></uni-segmented-control>
		</uvsticky>
		<view class="order-content">
			<view class='kong' v-if="orders.length==0">
				<image mode="widthFix" src="/static/sjimg/no.png" class="iconsss"></image>
			</view>
			<view class="order-items" v-else>
				<view class="order-item" v-for="item in orders" :key="item.id">
					<view class="dinor">
						<text class="dyct">订单号：{{item.bid}}</text>
						<text class="dydct" v-if="item.status == 1&&item.level==10&& item.countdown > 0">剩余支付时间：{{ formatCountdown(item.countdown) }} </text>
					</view>
					<view class="ordercent">
						<image :src="item.pro_pic" mode="scaleToFill" class="imgss" v-if="item.level==10"></image>
						<image :src="imgUrls+item.pro_pic" mode="scaleToFill" class="imgss1" v-if="item.level==11"></image>
						<view class="orderight">
							<view class="orderightxt">{{item.pro_name}}</view>
							<view class="orderighxtxt" v-if="item.level==10"> × {{item.num}}张 </view>
							<view class="orderighxtxt" v-if="item.level==11"> × {{item.num}} </view>
							<view class="buytime">{{item.memo}}</view>
							<view class="buytime">下单时间：{{item.create_date}}</view>
						</view>
						<view class="buyss" @click="buy(item)" v-if="item.status == 1&&item.level==10">付款</view>
						<view class="buyss" @click="buys(item)" v-if="item.status == 1&&item.level==11">付款</view>
						<view class="buyss" @click="buyshop(item)" v-if="item.status == 1&&item.level==null">付款</view>
					</view>
					<view class="qucssd">
						<text class="text-price">总价：{{item.money_pay}}元</text>
						<text @click="delorder(item.id)" class="decss" v-if="item.status == 1">删除订单</text>
						<text @click="lookorder(item.bid)" class="decss" v-if="item.status != 1&&item.level==10">查看</text>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="paypopup" type="bottom" background-color="#fff" border-radius="20px 20px 0 0">
			<view class="logins">
				<view class="cantxt1"> 下单支付 </view>
				<view class="uisss1">
					<text class="text-price">{{payinfo.money_pay}}</text>
					<text class="text1">{{payinfo.pro_name}}</text>
					<text class="text2">订单号:{{payinfo.bid}}</text>
				</view>
				<view class="btns" @click="buysure">支付</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref , onMounted , onUnmounted } from 'vue';
	import { onShow , onReachBottom , onHide } from '@dcloudio/uni-app';
	import uvsticky from '@/uni_modules/uv-sticky/components/uv-sticky/uv-sticky';
	import { apiGorlist , apiGordrinfo , apiDelmovie } from '@/api/upapi.js';
	import dayjs from 'dayjs';

	const current = ref(0);
	// const imgurl= ref('https://h.foomi.cn/ruyue/upload/');
	const imgurl = ref('https://m.aqbwg.cn/sourse/merchant/');
	const imgUrls = ref('https://m.aqbwg.cn/sourse/xiaowan/product/');
	const orders = ref([]);
	const payinfo= ref({});
	const paypopup =ref(null);
	const isNext = ref(false);
	const pages = ref(1);
	const items = ref([{id:0,name:'全部'},{id:2,name:'待支付'},{id:4,name:'已支付'},{id:5,name:'已完成'},{id:10,name:'已取消'}]);
	const timers = ref({}); 
	
	const getList = async() => {
	    const idx = uni.getStorageSync('xwmemberId');
	    try {
	        let res = await apiGorlist({
	            page: pages.value,
	            pageSize: 10,
	            memberId: idx,
	            status: current.value
	        });
	        if (res.data.result === 0) {
	            var data = res.data.object.data;
	            if (pages.value === 1) {
	                orders.value = data;
	            } else {
	                orders.value = orders.value.concat(data);
	            }
	            if (data.length >= 10) {
	                pages.value = pages.value + 1;
	            } else {
	                isNext.value = true;
	            }
	            setupCountdowns();
	        } else {
	            uni.showToast({ title: res.data.msg, icon: 'none' });
	        }
	    } catch (error) {
	        console.error('获取数据失败', error);
	    }
	};
	const lookorder = async(e) =>{  uni.navigateTo({ url: '/pagesA/index/discount?id='+e }) };
	const buy = async(e) =>{
		if(e.pay_info){
			var data = JSON.parse(e.pay_info);
			uni.requestPayment({
				appId: data.appId,
				provider: 'wxpay',
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: function(res) {
					uni.showToast({ title: '支付成功', icon: 'none' });
					pages.value=1;
					isNext.value = false;
					orders.value=[];
					getList();
				},
				fail: function(err) {}
			});
		}else{
			const seatArray = e.memo.split(',');
			const result = seatArray.map(seat => ({ seatName: seat.trim() }));
			let dsxnfo = {
				orderPrice:  Number(e.money_total * 100),
				outOrderSn: e.bid,
				showPrices:  Number(e.money_pay * 100), 
				filmName: e.pro_name,
				zuowei: result
			};
			const encodedData = encodeURIComponent(JSON.stringify(dsxnfo));
			uni.navigateTo({ url: `/pagesA/movie/pay?data=${encodedData}`})
		}
	};
	const buys = async(e) =>{
		if(e.pay_info){
			var data = JSON.parse(e.pay_info);
			uni.requestPayment({
				appId: data.appId,
				provider: 'wxpay',
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: function(res) {
					uni.showToast({ title: '支付成功', icon: 'none' });
					pages.value=1;
					isNext.value = false;
					orders.value=[];
					getList();
				},
				fail: function(err) {}
			});
		}
	};
	const buyshop = async(e) =>{
		if(e.pay_info){
			var data = JSON.parse(e.pay_info);
			my.tradePay ({
				tradeNO: data.tradeNO,
				success: res => {
					if(res.resultCode=="9000"){
						uni.showToast({ title: '支付成功', icon: 'none' });
						pages.value=1;
						isNext.value = false;
						orders.value=[];
						getList();
					}else{
						uni.showToast({ title: '支付失败', icon: 'none' });
						paypopup.value.close();
					}
				},
				fail: error => {
					console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
				},
			});
		}else{
			payinfo.value=e;
			paypopup.value.open();
		}
	};
	const buysure  = async () => {
		const idx = uni.getStorageSync('xwmemberId');
		const xwmemberInfo = uni.getStorageSync('xwmemberInfo');
		try {
			let res = await apiBuy({
				memberId: idx,
				merchantId:payinfo.value.merchant_id,
				type:5,
				bid:payinfo.value.bid,
				openid:xwmemberInfo.ali_uId
			});
			if(res.data.result==0){
				const orderno =  JSON.parse(res.data.object);
				my.tradePay ({
					tradeNO: orderno.tradeNO,
					success: res => {
						if(res.resultCode=="9000"){
							uni.showToast({ title: '支付成功', icon: 'none' });
							paypopup.value.close();
							pages.value=1;
							isNext.value = false;
							orders.value=[];
							getList();
						}else{
							uni.showToast({ title: '支付失败', icon: 'none' });
							paypopup.value.close();
						}
					},
					fail: error => {
						console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
					},
				});
			}
		} catch (error) {
			console.error('获取数据失败', error);
		}
	};
	const setupCountdowns = () => {
	  const now = Date.now();
	  orders.value.forEach(order => {
	    if (order.status === 1&&order.level==10) {
	      const createDate = new Date(order.create_date).getTime();
	      const diff = 5 * 60 * 1000 - (now - createDate);
	      
	      order.countdown = Math.ceil(diff / 1000);
	      // 添加响应式字段
	      if (!order.hasOwnProperty('countdown')) {
	        order.countdown = 0;
	      }
	      if (diff > 0) {
	        startCountdown(order);
	      } else {
	        order.countdown = 0;
	        orders.value = [...orders.value]; // 触发更新
	      }
	    }
	  });
	};
	
	const startCountdown = (order) => {
	  clearInterval(timers.value[order.id]); // 先清除已有定时器
	  order.countdown = Math.max(0, order.countdown); // 确保非负数
	  
	  timers.value[order.id] = setInterval(() => {
	    if (order.countdown > 0) {
	      order.countdown -= 1;
	      orders.value = [...orders.value];
	    } else {
	      clearInterval(timers.value[order.id]);
	      delete timers.value[order.id];
		  console.log('1=======',order.delOrderCalled);
	      if (!order.delOrderCalled) {
			  console.log('2=======',order.delOrderCalled);
	        order.delOrderCalled = true;
	        delorder(order.id);
	      }
	    }
	  }, 1000);
	};
	
	const onClickItem = (e) => {
	    if (current.value != e.currentIndex) {
	        current.value = e.currentIndex;
	    }
	    pages.value = 1;
	    orders.value = [];
	    clearAllTimers(); // 清理所有倒计时器
	    getList();
	};
	
	const clearAllTimers = () => {
	    Object.values(timers.value).forEach(timer => clearInterval(timer));
	    timers.value = {};
	};
	
	const delorder = async(e) => {
	    try {
	        let res = await apiDelmovie({ id: e });
	        if (res.data.result === 0) {
	            uni.showToast({ title: res.data.object, icon: 'none' });
	            pages.value = 1;
	            current.value = 0;
	            orders.value = [];
	            getList();
	        } else {
	            uni.showToast({ title: res.data.msg, icon: 'none' });
	        }
	    } catch (error) {
	        console.error('获取数据失败', error);
	    }
	};
	
	const formatCountdown = (seconds) => {
	    const minutes = Math.floor(seconds / 60);
	    const secs = seconds % 60;
	    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
	};
	
	onShow(() => {
	  current.value = 0;
	  pages.value = 1;
	  orders.value = [];
	  getList();
	  
	  // 恢复所有有效倒计时
	  orders.value.filter(o => o.status === 1).forEach(order => {
	    if (order.countdown > 0) startCountdown(order);
	  });
	});
	
	onHide(() => {
	    clearAllTimers(); // 清理所有倒计时器
	});
	
	onReachBottom(() => {
		if (!isNext.value) { getList(); }
	});
</script>
<style>
	
</style>
<style scoped lang="scss">
	.topbox{
		padding: 88rpx 20rpx 0rpx;
		background-color: #fff;
		.btimg{
			width: 180rpx;
		}
	}
	.order-content {
		padding: 0 0 30rpx;
		.kong {
			margin: 240upx auto 0;
			display: flex;
			justify-content: center;
			.iconsss{
				width:400rpx;
			}
		}
	}
	.order-items{
		padding: 20rpx;
		.order-item{
			padding: 20rpx;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 15rpx;
			.ordercent{
				display: flex;
				margin: 20rpx 0;
				align-items: center;
				justify-content: space-between;
			}
			.dinor{
				display: flex;
				align-items: center;
				justify-content: space-between;
				.dyct{
					color: #3b3b3b;
					font-size: 24rpx;
				}
				.dydct{
					color: #ff0000;
					font-size: 24rpx;
				}
			}
			.imgss {
				width: 140upx !important;
				height: 180upx !important;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}
			.imgss1{
				width: 180upx !important;
				height: 180upx !important;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}
			
			.orderight {
				height: 180upx;
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				.orderightxt{
					font-size: 29rpx;
					font-weight: bold;
				}
				.orderightxt1{
					font-size: 24rpx;
					color: #666666;
				}
				.orderighxtxt{
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 26rpx;
				}
			}
			.buyss{
				padding: 10rpx 20rpx;
				border: 2rpx solid #ff4a82;
				border-radius: 30rpx;
				font-size: 26rpx;
				color: #fff;
				background-color: #ff4a82;
			}
			.wuliuorder{
				color: #ff4a82;
				margin-bottom: 20rpx;
			}
			.qucssd{
				display: flex;
				align-items: center;
				justify-content: space-between;
				.text-price {
					color: #8b8b8b;
					font-size: 24rpx;
				}
				.decss{
					font-size: 24rpx;
					padding: 4rpx 10rpx;
					color: #8b8b8b;
					border: 2rpx solid #8b8b8b;
					border-radius: 20rpx;
				}
			}
			
			.buytime{
				font-size: 24rpx;
				color: #8b8b8b;
			}
		}
	}
	.logins{
		background-color: #fff;
		padding: 30rpx 30rpx 120rpx;
		border-radius: 30rpx 30rpx 0 0;
		display: flex;
		flex-direction: column;
		.cantxt1{
			text-align: center;
			font-size: 28rpx;
			color: #646464;
		}
		.uisss1{
			margin: 60rpx 0 100rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			.text-price {
				color: #ff4a82;
				font-size: 60rpx;
				font-weight: bolder;
			}
			
			.text-price::before {
				content: '￥';
				color: #ff4a82 !important;
				font-size: 26rpx !important;
			}
			.text1{
				margin: 10rpx 0;
				font-size: 26rpx;
				color: #646464;
			}
			.text2{
				font-size: 26rpx;
				color: #646464;
			}
		}
		.btns{
			background-color: #ff4a82;
			padding: 30rpx ;
			color: #fff;
			text-align: center;
			border-radius: 100rpx;
		}
	}
</style>